-- JokStick
-- Codea 游戏手柄类 ver1.1
-- 作者：AK2806 QQ：642207429
-- 使用时请不要删除这条信息
-- 转载请注明
JoyStick = class()
function JoyStick:init(x,y,size)
    self.x = x
    self.y = y
    self.touches = {}
    self.size = size -- 摇杆大小
    self.ID = nil
    self.touchVec2 = vec2(0, 0) -- 摇杆位置数据
    self.directionVec2 = vec2(0, 0)
    self.isTouched = false
end
function JoyStick:draw() -- 在draw()中调用
    if self.visible == false then return end
    for key, touch in pairs(self.touches) do
        local module = math.sqrt((touch.x - self.x) ^ 2 + (touch.y - self.y) ^ 2)
        if module <= self.size / 2 then
            self.ID = touch.id
            self.isTouched = true
            self.touchVec2 = vec2(touch.x - self.x, touch.y - self.y)
        else
            if touch.state == MOVING and touch.id == self.ID then
                local vector = vec2(touch.x - self.x, touch.y - self.y)
                self.touchVec2 = self.size / 2 * vector:normalize()
            end
        end
    end
    if self.touchVec2:len() > 0 then
        self.directionVec2 = self.touchVec2:normalize()
    else
        self.directionVec2 = vec2(0, 0)
    end
    pushStyle()
    rectMode(CENTER)
    
 --------------------- 增加内容处 ---------------------  
    fill(127, 127, 127, 255)
    noStroke()
    rect(self.x,self.y,self.size*1.4,self.size*1.4)
    fill(62, 62, 62, 255)
    text("Moving Camera",self.x/2,self.y/5)
-------------------------------------------------------
    fill(255, 20)
    stroke(255, 200)
    strokeWidth(7)
    ellipse(self.x, self.y, self.size)
    
    if self.isTouched == true then
        fill(255, 50)
        stroke(255)
        strokeWidth(3)
        ellipse(self.x + self.touchVec2.x, self.y + self.touchVec2.y, self.size / 2)
    end
    popStyle()
end
function JoyStick:touched(touch)
    -- if self.visible == false or self.enabled == false then return false end
    if touch.state == ENDED then
        self.touches[touch.id] = nil
        self.ID = nil
        self.isTouched = false
        self.touchVec2 = vec2(0, 0)
    else
        self.touches[touch.id] = touch
    end
end